﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Speech.Recognition;
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Speech.Synthesis;
using System.IO;
using System.Collections;

namespace TROLI
{
    class Program
    {


        [DllImport("kernel32.dll")]
        static extern int GetConsoleWindow();

        [DllImport("user32.dll")]
        static extern bool ShowWindow(int hWnd, int nCmdShow);

        [DllImport("PowrProf.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern bool SetSuspendState(bool hiberate, bool forceCritical, bool disableWakeEvent); //cau lenh sleep window

        static ManualResetEvent _completed = null;

        static SpeechSynthesizer _synthesizer = new SpeechSynthesizer();

        static ArrayList lenh = new ArrayList();
        static ArrayList lenhthucthi = new ArrayList();
        static ArrayList thamso = new ArrayList();

        static void Main(string[] args)
        {
            ShowWindow(GetConsoleWindow(), 0);
            using (SpeechRecognitionEngine _recognizer = new SpeechRecognitionEngine())
            {
                _completed = new ManualResetEvent(false);

                _recognizer.LoadGrammar(new Grammar(new GrammarBuilder("GOOD BYE MY CHILD")));

                lenh.Add("GOOD BYE MY CHILD");

                //Add a handler for the speech recognized event
                _recognizer.SpeechRecognized += _onSpeechRecognized;
                //configure input to the speech recognizer
                _recognizer.SetInputToDefaultAudioDevice();

                //start asynchronous, continous speech recognition
                _recognizer.RecognizeAsync(RecognizeMode.Multiple);
                //wait until speech recognition is completed

                Nhap();

                GrammarBuilder builder;
                Grammar grammar;
                foreach (string st in lenh)
                {
                    if (st != "")
                    {
                        builder = new GrammarBuilder(st);
                        grammar = new Grammar(builder);
                        _recognizer.LoadGrammar(grammar);
                    }
                }
                _completed.WaitOne();
                _synthesizer.Speak("Goobye my master. See you again");
                //dispose the speech recognition engine
                _recognizer.Dispose();
                _synthesizer.Dispose();

            };

        }

        private async static void Nhap()
        {
            string pathFile = Directory.GetCurrentDirectory() + "\\caulenh.txt";
            while (NapDuLieu(pathFile) == -1)
            {
                ShowWindow(GetConsoleWindow(), 5);
                Console.WriteLine("Please the enter command path again: ");
                _synthesizer.Speak("Please the enter command path again or exit: ");
                var pathFile2 = await Task<string>.Run(() => { return Console.ReadLine(); });
                pathFile = pathFile2;
                ShowWindow(GetConsoleWindow(), 0);
            }
            
        }

        private static void _onSpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            int i;
            for (i = 0; i < lenh.Count; i++) //tim kiem lenh o vi tri nao de dua ra lenh thuc thi tuong ung
            {
                string lenhx = lenh[i].ToString();
                if (e.Result.Text == lenhx)
                    break;
            }
            if (i < lenh.Count)
            {
                Console.WriteLine(e.Result.Text);
                if (e.Result.Text == "GOOD BYE MY CHILD") //thoat chuong trinh
                {
                    _completed.Set();

                }
                else if (e.Result.Text == "SLEEP MY COMPUTER")
                {
                    SetSuspendState(false, true, true);
                }
                else if (e.Result.Text.Substring(0, 8) == "MY CHILD")
                {
                    _synthesizer.Speak(lenhthucthi[i].ToString());
                }
                else if (e.Result.Text == "SHOW WINDOW")
                    ShowWindow(GetConsoleWindow(), 5);
                else if (e.Result.Text == "HIDDEN WINDOW")
                {
                    ShowWindow(GetConsoleWindow(), 0);
                }
                else
                {
                    string filename = lenhthucthi[i].ToString();
                    string argument = thamso[i].ToString();
                    _synthesizer.Speak("Watting minutes");
                    Process myProcess = new Process();
                    myProcess.StartInfo.FileName = filename;
                    if (argument != "") myProcess.StartInfo.Arguments = argument;
                    myProcess.Start();
                    _synthesizer.Speak("Finished");
                }
            }
        }

        private static void _onSpeechRejected(object sender, SpeechRecognitionRejectedEventArgs e)
        {
            _synthesizer.Speak("Sorry. Try again a little bit");
        }

        private static int NapDuLieu(string pathFile)
        {

            try
            {
                using (StreamReader sr = new StreamReader(pathFile))
                {
                    string line;
                    while (((line = sr.ReadLine()) != null) && (line != ""))
                    {
                        if (line[0] == '1')
                        {
                            line = line.Remove(0, 2);
                            lenh.Add(line.Trim().ToUpper());
                        }
                        else if (line[0] == '2')
                        {
                            line = line.Remove(0, 2);
                            lenhthucthi.Add(line.Trim());
                        }
                        else if (line[0] == '3')
                        {
                            line = line.Remove(0, 2);
                            thamso.Add(line.Trim());
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _synthesizer.Speak("I can't load file");
                return -1; //error
            }
            return 1;
        }
        
    }
}
